import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import LunaServer.core.LunaServer;
import LunaServer.routing.Route;

/**
 * Token验证路由处理器
 * 处理/tokenauth路径的请求
 */
public class TokenAuthRoute implements Route {

    private final LunaServer server;

    public TokenAuthRoute(LunaServer server) {
        this.server = server;
    }

    /**
     * 处理HTTP请求
     * 
     * @param exchange HttpExchange对象
     * @return 响应内容
     */
    public String handleRequest(HttpExchange exchange) throws IOException {
        String response = "";
        int responseCode = 200;

        try {
            // 读取请求体
            String requestBody = "";
            try (InputStream is = exchange.getRequestBody()) {
                requestBody = new String(is.readAllBytes(), StandardCharsets.UTF_8);
            }

            // 解析请求数据
            Gson gson = new Gson();
            Map<String, String> requestData = gson.fromJson(requestBody, Map.class);

            String token = requestData.get("token");

            // 构造响应
            Map<String, Object> result = new HashMap<>();

            // 实际的token验证（查询数据库）
            Map<String, Object> userData = validateToken(token);
            if (userData != null) {
                result.put("code", "200");
                result.put("status", "valid");
                result.put("userData", userData);
            } else {
                result.put("code", "200");
                result.put("status", "invalid");
            }

            result.put("time", Instant.now().toString());
            response = gson.toJson(result);

            // 设置响应头
            exchange.getResponseHeaders().set("Content-Type", "application/json");
        } catch (Exception e) {
            handleMethodNotAllowed(exchange);
        }

        // 发送响应
        exchange.sendResponseHeaders(responseCode, response.getBytes(StandardCharsets.UTF_8).length);
        return response;
    }

    /**
     * 验证token有效性
     * 
     * @param token 用户token
     * @return 用户数据，如果token无效则返回null
     */
    private Map<String, Object> validateToken(String token) {
        // 简单示例：从token中提取用户名（实际应该查询数据库验证token）
        if (token != null && token.startsWith("token_for_")) {
            String username = token.replace("token_for_", "");

            // 从LunaServer实例获取数据库连接参数
            String dbUrl = server.getDbUrl();
            String dbUser = server.getDbUser();
            String dbPass = server.getDbPass();

            String sql = "SELECT username, age, is_active FROM users WHERE username = ?";

            try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
                    PreparedStatement pstmt = conn.prepareStatement(sql)) {

                pstmt.setString(1, username);

                try (ResultSet rs = pstmt.executeQuery()) {
                    if (rs.next()) {
                        Map<String, Object> userData = new HashMap<>();
                        userData.put("userName", rs.getString("username"));
                        userData.put("userLevel", rs.getInt("age")); // 简单示例
                        userData.put("isVIP", rs.getBoolean("is_active"));
                        return userData;
                    }
                }

            } catch (SQLException e) {
                System.err.println("Database error during token validation: " + e.getMessage());
                e.printStackTrace();
            }
        }

        return null; // 验证失败
    }
}